package com.wayz.serivce;

import com.wayz.annotation.DYGTransactional;
import com.wayz.constants.CAuditorType;
import com.wayz.constants.PageVo;
import com.wayz.entity.dto.AuditorDto;
import com.wayz.entity.dto.AuditorQueryDto;
import com.wayz.entity.pojo.auditor.DAuditor;
import com.wayz.entity.pojo.auditor.DAuditorUser;
import com.wayz.entity.redis.RAuditor;
import com.wayz.entity.redis.RAuditorUser;
import com.wayz.entity.vo.AuditorVO;
import com.wayz.exception.WayzException;
import com.wayz.mapper.DAuditorDAO;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RedisUtils;
import com.wayz.service.AuditorService;
import com.wayz.service.AuditorUserService;
import com.wayz.util.FileMD5Helper;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 审核方服务实现类
 *
 * @author mike.ma@wayz.ai
 */
@Service("auditorService")
@org.apache.dubbo.config.annotation.Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class AuditorServiceImpl implements AuditorService {

    /**
     * Redis工具类
     */
    @Resource(name = "redisUtils")
    private RedisUtils redisUtils;

    /**
     * 审核方DAO
     */
    @Resource(name = "dAuditorDAO")
    private DAuditorDAO dAuditorDAO;

    /**
     * 审核方用户服务
     */
    @Resource(name = "auditorUserService")
    private AuditorUserService auditorUserService;

    /**
     * 审核方列表
     *
     * @param myId 我的ID
     * @param dto  审核方
     * @return
     */
    @Override
    public PageVo<AuditorVO> queryAuditor(Long myId, AuditorQueryDto dto) throws WayzException {
        PageVo<AuditorVO> page = new PageVo<AuditorVO>();
        Integer count = dAuditorDAO.count(dto);
        if (count <= 0) {
            return page;
        }
        List<AuditorVO> list = dAuditorDAO.query(dto);
        for (AuditorVO vo : list) {
            vo.setTypeName(CAuditorType.getDescription(vo.getType()));
            vo.setCreatedTime(vo.getCreatedTime().substring(0, 19));
        }
        page.setList(list);
        page.setTotalCount(count);
        return page;
    }

    /**
     * 获取审核方详情
     *
     * @param myId 我的标识
     * @param id   审核方标识
     * @return
     * @throws WayzException
     */
    @Override
    public AuditorVO getAuditor(Long myId, Long id) throws WayzException {
        AuditorVO vo = dAuditorDAO.get(id);
        if (vo == null) {
            throw new WayzException("审核方不存在");
        }
        vo.setTypeName(CAuditorType.getDescription(vo.getType()));
        vo.setCreatedTime(vo.getCreatedTime().substring(0, 19));
        return vo;
    }

    /**
     * 创建审核方
     *
     * @param myId   我的ID
     * @param dto 创建实体类
     * @throws WayzException
     */
    @Override
    @DYGTransactional
    public void createAuditor(Long myId, AuditorDto dto) throws WayzException {
        if (dAuditorDAO.existByName(dto.getName(), null)) {
            throw new WayzException("审核方名称已存在!");
        }
        if (dAuditorDAO.existByPhone(dto.getTelephone(), null)) {
            throw new WayzException("审核方手机号已存在!");
        }
        // 获取审核方编号
        DAuditor create = new DAuditor();
        BeanUtils.copyProperties(dto, create);
        Long id = redisUtils.incrBy(BeanIdKeyEnum.AUDITOR.getKey(), RedisUtils.STEP_SIZE);
        create.setId(id);
        create.setStatus((short) 1);
        create.setCreatorId(myId);
        dAuditorDAO.create(create);

        // 初始化审核方管理员账号
        Long userId = redisUtils.incrBy(BeanIdKeyEnum.AUDITOR_USER.getKey(), RedisUtils.STEP_SIZE);
        DAuditorUser userCreate = new DAuditorUser();
        userCreate.setId(userId);
        userCreate.setAuditorId(id);
        userCreate.setUsername(dto.getTelephone());
        userCreate.setTelephone(dto.getTelephone());
        userCreate.setPassword(FileMD5Helper.getMD5String("123456"));
        userCreate.setCreatorId(myId);
        auditorUserService.createUser(myId, userCreate);

        // 维护缓存
        RAuditor rAuditor = new RAuditor();
        BeanUtils.copyProperties(create, rAuditor);
        redisUtils.hPutBeanAsHash(RAuditor.getKey(id), rAuditor);

        RAuditorUser rAuditorUser = new RAuditorUser();
        BeanUtils.copyProperties(userCreate, rAuditorUser);
        redisUtils.hPutBeanAsHash(RAuditorUser.getKey(id), rAuditorUser);
    }

    /**
     * 修改审核方
     *
     * @param myId   我的ID
     * @param dto 实体类
     * @throws WayzException
     */
    @Override
    public void modifyAuditor(Long myId, AuditorDto dto) throws WayzException {
        AuditorVO vo = dAuditorDAO.get(dto.getId());
        if (vo == null) {
            throw new WayzException("审核方不存在");
        }
        if (dAuditorDAO.existByName(dto.getName(), dto.getId())) {
            throw new WayzException("审核方名称已存在!");
        }
        if (dAuditorDAO.existByPhone(dto.getTelephone(), dto.getId())) {
            throw new WayzException("审核方手机号已存在!");
        }
		DAuditor modify = new DAuditor();
		BeanUtils.copyProperties(dto, modify);
        dAuditorDAO.modify(modify);

        // 更新Redis
        RAuditor rAuditor = redisUtils.hGetAllAsBean(RAuditor.getKey(modify.getId()), RAuditor.class);
        rAuditor.setName(modify.getName());
        rAuditor.setContacts(modify.getContacts());
        rAuditor.setTelephone(modify.getTelephone());
        redisUtils.hPutBeanAsHash(RAuditor.getKey(modify.getId()), rAuditor);
    }

    /**
     * 修改审核方状态
     *
     * @param id     审核方ID
     * @param status 审核方状态(1:启用 0:禁用;)
     * @return
     */
    @Override
    public Integer modifyAuditorStatus(Long myId, Long id, Short status) throws WayzException {
        AuditorVO vo = dAuditorDAO.get(id);
        if (vo == null) {
            throw new WayzException("审核方不存在");
        }
        // 修改状态
        Integer count = dAuditorDAO.updateAuditorStatus(id, status);

        // 维护缓存
        redisUtils.hPut(RAuditor.getKey(id), RAuditor.STATUS, status.toString());

        // 返回
        return count;
    }

    /**
     * 删除审核方
     *
     * @param myId 我的ID
     * @param id   审核方ID
     * @throws WayzException
     */
    @Override
    public void deleteAuditor(Long myId, Long id) throws WayzException {
        AuditorVO vo = dAuditorDAO.get(id);
        if (vo == null) {
            throw new WayzException("审核方不存在");
        }

        // 删除
        DAuditor modify = new DAuditor();
        modify.setId(id);
        modify.setIsDeleted(true);
        dAuditorDAO.modify(modify);

        // 维护缓存
        redisUtils.delete(RAuditor.getKey(id));
    }

    /**
     * 审核方重置密码
     *
     * @param myId        我的ID
     * @param username    审核方名称
     * @param newPassword 新的密码
     * @throws WayzException
     */
    @Override
    public void resetAuditorPassword(Long myId, String username, String newPassword) throws WayzException {
        auditorUserService.resetUserPassword(username, newPassword);
    }

}
